﻿//全局变量
var table, myGrid, ised = "";
$(document).on('ready', function () {
    $("#txt_file").fileinput({ showCaption: false });
});

$(document).ready(function () {


    GetMenuButtonList('btnOp');
    //#region datatable初始化及值绑定
    $.extend($.fn.dataTable.defaults, {
        dom: 'rt<"#dt-bottom.row"<"col-xs-2"l><"col-xs-7"p><"col-xs-3"i>>'
    });
    var scrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
    //适应窗口大小变化
    $(window).resize(function () {
        var newScrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
        $('.dataTables_scrollBody').css('height', newScrollY);
    });
    myGrid = {
        id: 'dt_admin',
        isenable: false,//是否需要禁用启用按钮
        scrollY: scrollY,
        scrollX: true,
        paging: true,
        hasIndex: true,
        multiSelect: false,
        processing: true,
        serverSide: true,
        columns: [
                { data: "Row", title: "#" },
                { data: "companys", title: "保险公司" },//"visible": false 
                { data: "policynumber", title: "保单号" },
                { data: "insuran", title: "被保险人" },
                { data: "insurancard", title: "被保险人身份证号" },
                { data: "policyagent", title: "保单代理人" }//,
                //{ data: "businessattribution", title: "业务归属机构" },
                //{ data: "businessdepartment", title: "业务归属部门" },
                //{ data: "businessowner", title: "业务归属人员" }
        ],
        columnDefs: [],
        order: [[1, 'asc']],
        data: {},
        ajax: function (data, callback, settings) {
            //封装请求参数
            var reUrl = 'GetPolicies';
            var order = data.columns[data.order[0].column].data + " " + data.order[0].dir;
            var pagesize = data.length;
            var pageno = (data.start / data.length) + 1;
            //查询条件
            var searchData = { pagesize: pagesize, pageno: pageno, order: order, query: $('#query').val(), startTime: $('#date_st').val(), endTime: $('#date_ed').val() };
            //ajax请求数据
            $.ajax({
                type: "GET",
                url: reUrl,
                cache: false,//禁用缓存
                data: searchData,//传入组装的参数
                dataType: "json",
                //headers: param,//请求头参数
                success: function (result, status, xhr) {
                    //封装返回数据
                    var returnData = {};
                    returnData.draw = data.draw; //这里直接自行返回了draw计数器,应该由后台返回
                    returnData.recordsTotal = result.TotalCount;
                    total_curr = result.TotalCurr;
                    returnData.recordsFiltered = result.TotalCount; //后台不实现过滤功能，每次查询均视作全部结果
                    returnData.data = result.Entity; //返回的数据列表
                    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                    callback(returnData);//将你的返回的data转为datatables能识别的数据格式作为参数返回ajax的callback回调中。
                }
            });
        }
    }
    table = DataBind(myGrid);
    //#endregion 
    $('#btnPolicySave').click(function () {
        AjaxSave();
    });
    //$('#datetimepicker_st,#datetimepicker_ed').datetimepicker({
    //    format: 'YYYY-MM-DD'
    //});
    $('#btnInquire').click(function () {
        loadTableData();
    })
});


//新增
var Btn_Add = function () {
    $('#title').text("录入保单");
    $('#id').val('-1');
    $("#company").val('');
    $("#policynumber").val('');
    $("#insuran").val('');
    $("#insurancard").val('');
    $("#policyagent").val('');
    $("#businessattribution").val('');
    $("#businessdepartment").val('');
    $("#businessowner").val('');
    $('#InsuranceAccountAddModal').modal('show');
}

//编辑
var Btn_Edit = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选中要编辑的数据！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    var seletedItem = table.rows('.selected').data()[0];
    $('#title').text("保单编辑");
    $('#id').val(seletedItem.id);
    $("#company").val(seletedItem.company);
    $("#policynumber").val(seletedItem.policynumber);
    $("#insuran").val(seletedItem.insuran);
    $("#insurancard").val(seletedItem.insurancard);
    $("#policyagent").val(seletedItem.policyagent);
    $("#businessattribution").val(seletedItem.businessattribution);
    $("#businessdepartment").val(seletedItem.businessdepartment);
    $("#businessowner").val(seletedItem.businessowner);

    $('#InsuranceAccountAddModal').modal('show');
}

//刷新datatable
function loadTableData() {
    table.ajax.reload();
}

function GetValues() {
    var obj = {};
    obj.id = $('#id').val();
    obj.company = $("#company").val();
    obj.policynumber = $("#policynumber").val();
    obj.insuran = $("#insuran").val();
    obj.insurancard = $("#insurancard").val();
    obj.policyagent = $("#policyagent").val();
    obj.businessattribution = $("#businessattribution").val();
    obj.businessdepartment = $("#businessdepartment").val();
    obj.businessowner = $("#businessowner").val();
    return obj;
}
function ShowInfo(msg) {
    $.notify({
        message: '<i class="fa fa-exclamation"></i> ' + msg,
        status: "danger",
        pos: "bottom-right"
    });
}

//function checkLength(field) {
//    var str;
//    var count = 0;
//    var value = field.value;
//    var length = field.maxLength;
//    var desc = field.placeholder;
//    //如果description属性不存在，则用name属性
//    if (desc == null)
//        desc = field.placeholder;
//    if (value == "") {
//        return true;
//    }

//    //如果maxlength属性不存在，则返回
//    if (isNaN(parseInt(length, 18)))
//        return true;
//    for (var i = 0; i < value.length; i++) {
//        str = escape(value.charAt(i));
//        if (str.substring(0, 2) == "%u" && str.length == 6)
//            count = count + 2;
//        else
//            count = count + 1;
//    }
//    if (count > length) {
//        errorMessage(desc + "输入的内容超长！\n" + desc + "的最大长度为" + length + "个数字！\n请重新输入！");
//        field.focus();
//        field.select();
//        return false;
//    }
//    else if (count < length) {
//        errorMessage(desc + "输入的身份证号小于18位！\n" + desc + "的最大长度为" + length + "个数字！\n请重新输入！");
//        field.focus();
//        field.select();
//        return false;
//    }
//    return true;
//}

function AjaxSave() {
    var obj = GetValues();
    var cd = /^[A-Za-z0-9]{18}/;// /(\d{18}) || (\d{17}[A-Z]{1})/;//定义身份证匹配算法
    var legalIdCard = $("#insurancard").val();//获取前台界面字段值
    if (legalIdCard != null && legalIdCard != "") {//运用匹配方法直接判断
        if (cd.test(legalIdCard) == false) {
            alert("输入身份证号不合法!");
            $("#insurancard").val("");//将前台输入值置为空
            return false;
        }
    }
    else if (legalIdCard == "") {
        alert("请输入身份证号!");
        $("#insurancard").val("");//将前台输入值置为空
        return false;
    }

    //var str = /^[A-Za-z0-9]{18}/;
    //if (str.test($("#insurancard").val())) {
    //    alert("验证通过");
    //} else {
    //    alert("验证错误，只能是数字字母组成的18位长度的字符串");
    //}

    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "SavePloicy?t=" + new Date().getTime(),
        data: "{json:'" + $.toJSON(GetValues()) + "'}",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                $('#InsuranceAccountAddModal').modal('hide');
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}
var Btn_Import = function () {
    $('#ImportModal').modal('show');
}

var Btn_Down = function () {
    window.location.href = "../../template/保单数据模板.xlsx";
}

//删除
var Btn_Delete = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择要删除的数据！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    bconfirm("确定删除？", LogDelete);
}
//删除方法
function LogDelete() {
    var ids = [];
    for (var i = 0; i < table.rows('.selected').data().length; i++) {
        ids.push(table.rows('.selected').data()[i].id);
    }
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "DeletePloicies?ids=" + ids.join() + "&t=" + new Date().getTime(),
        data: "",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}
